package com.hu.config.comment;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
    protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
       public static final String DEFAULT_ERROR_VIEW = "error";//对应templates下的error.html

         //返回错误页面如果找不到,会返回json，或者在
//        @ExceptionHandler(value = Exception.class)//如果使用自定义异常,改变value值就行如:value=MyException.class
//        public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
//            ModelAndView mav = new ModelAndView();
//            mav.addObject("exception", e);
//            mav.addObject("url", req.getRequestURL());
//            mav.setViewName(DEFAULT_ERROR_VIEW);
//           return mav;
//        }

    /**
     * 以json格式返回，在@ExceptionHandler之后加入@ResponseBody即可
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map defaultErrorHandler(HttpServletRequest req, Exception e){
        //LOGGER.error("exception", e);
        Map m=new HashMap();
        m.put("status",500);
        m.put("message","服务端错误");
        m.put("error",e.getMessage());
        m.put("timestamp",System.currentTimeMillis());
        m.put("path",req.getRequestURI());
        return m;
    }


}
